package com.cazor.dgjq.app;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import gds.bduop.sm.sm2.SM2EnDecryption;
import gds.bduop.sm.sm3.SM3Digest;
import gds.bduop.utils.JinZhiZhuanHuanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class DgjqAppReqService {

    @Resource
    private DgjqApp dgjqApp;

    public JSONObject sendSensorData(JSONObject contentJson) {
        String url = dgjqApp.getHttpPrefix() + "/api/monitor/sensor/data";
        log.info("url: " + url);
        return this.send4Json(contentJson.toString(), url);
    }

    public JSONObject sendStatus(JSONObject contentJson) {
        String url = dgjqApp.getHttpPrefix() + "/api/monitor/sensor/status";

        return this.send4Json(contentJson.toString(), url);
    }

    public JSONObject sendSensorGroupData(JSONObject contentJson) {
        String url = dgjqApp.getHttpPrefix() + "/api/monitor/sensor/group/data";

        return this.send4Json(contentJson.toString(), url);
    }

    private String send(String contentJsonStr, String url) {
        JSONObject bodyJson = this.smEncrypt(contentJsonStr);
        try {
            log.info("bodyJson:{}", bodyJson.toString());
            String respStr = HttpRequest.post(url)
//                .header(Header.USER_AGENT, " http")//头信息，多个头信息多次调用此方法即可
//                .form(paramMap)//表单内容
                    .body(bodyJson.toString())
                    .timeout(10000)//超时，毫秒
                    .execute().body();
            return respStr;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private JSONObject send4Json(String contentJsonStr, String url) {
        String respStr = this.send(contentJsonStr, url);
        log.info("respStr:{}", respStr);
        if (StrUtil.isNotBlank(respStr)) {
            return this.smDecrypt(respStr);
        } else {
            return null;
        }
    }

    /**
     * 对需要发送的req内容 进行sm加密
     * @param jsonStr
     * @return
     */
    public JSONObject smEncrypt(String jsonStr) {

        //使用公钥对原始状态信息(json格式)进行SM2加密
        String content = SM2EnDecryption.encrypt(dgjqApp.getEncryptionPublicKey(),
                jsonStr.getBytes(StandardCharsets.UTF_8));

        //对原始状态信息（json格式）进行SM3摘要计算
        String sign = SM3Digest.encrypt(jsonStr);

        JSONObject rtn = new JSONObject();
        rtn.put("appId", dgjqApp.getAppId());
        rtn.put("content", content);
        rtn.put("sign", sign);

        return rtn;
    }

    /**
     * 针对 resp 的结果 做解码 如果返回的json中 包含 contentJson表示正常
     * @param respStr 接口返回的resp
     * @return 结果
     */
    public JSONObject smDecrypt(String respStr) {
        JSONObject respJson = JSON.parseObject(respStr);
        String encryptContentStr = respJson.getString("content");
        String sign = StrUtil.nullToDefault(respJson.getString("sign"), "");
        try {
            //使用解密密钥解密SM2返回消息
            byte[] decryptResults = SM2EnDecryption.decrypt(JinZhiZhuanHuanUtil.hexToByte(dgjqApp.getDecryptPrivateKey()),
                    JinZhiZhuanHuanUtil.hexToByte(encryptContentStr));
            String decryptContent = new String(decryptResults);
            //对解密后的消息使用SM3计算摘要
            String decryptContentSign = SM3Digest.encrypt(decryptContent);
            // sign验证
            if (sign.equals(decryptContentSign)) {
                respJson.put("contentJson", JSON.parseObject(decryptContent));
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return respJson;
    }
}
